package com.lmx.persistence.service;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;
import com.lmx.common.constants.CommonConstants;
import com.lmx.persistence.service.common.BaseCrudServiceImpl;
import com.lmx.repoDomain.exception.BusinessException;
import com.lmx.repoDomain.tmodel.ActivityOrder;
import com.lmx.repoDomain.tmodel.ActivityPlan;

@Service(value = "activityPlanService")
public class ActivityPlanServiceImpl extends BaseCrudServiceImpl<ActivityPlan>
		implements ActivityPlanService {
	private Log logger = LogFactory.getLog(this.getClass());

	@PersistenceContext
	private EntityManager em;
	@Autowired
	ActivityOrderService orderSrv;

	@Override
	public Boolean checkExist(ActivityPlan entity, Long tenantId) {
		Boolean rtn = false;
		if (entity.getId() != null) {
			ActivityPlan old = super.findOne(entity.getId());
			// 如果 day和时间 没有修改的话不需要判定是否存在,直接返回false
			rtn = (!(entity.getDay().getId().equals(old.getDay().getId())
					&& entity.getTime().equals(old.getTime()) && entity
					.getActivity().getId().equals(old.getActivity().getId())));
			if (!rtn) {
				return rtn;
			}
		}
		Map<String, Object> param = Maps.newHashMap();
		param.put("activity.id", entity.getActivity().getId());
		param.put("day.id", entity.getDay().getId());
		param.put("time", entity.getTime());
		param.put("tenant.id", tenantId);
		param.put("delStatus", CommonConstants.DEL_STATUS_NO_0);
		List<ActivityPlan> list = super.find(param);
		// 如果是修改要忽略本身的数据
		Integer dataCount = entity.getId() == null ? 0 : 1;
		rtn = (list != null && list.size() > dataCount);
		return rtn;
	}

	@Override
	public void checkDelete(ActivityPlan entity) {
		List<ActivityOrder> orders = this.orderSrv.find("activityPlan.id",
				entity.getId());
		if (orders != null && orders.size() > 0) {
			throw new BusinessException("",
					CommonConstants.ACTIVITY_ERROR_CODE.NOT_DELETE.lable(),
					"不能删除");
		}
	}
}
